package org.linlinjava.litemall.db.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.linlinjava.litemall.db.dao.OrderMapper;
import org.linlinjava.litemall.db.models.Order;
import org.linlinjava.litemall.db.service.OrderService;
import org.linlinjava.litemall.db.util.OrderUtil;
import org.linlinjava.litemall.db.vo.OrderVo;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>
    implements OrderService {

    @Override
    public int count(Long userId) {
        return baseMapper.selectCount(new LambdaQueryWrapper<Order>().eq(Order::getUserId, userId));
    }

    @Override
    public Order findById(Long userId, Long orderId) {
        return baseMapper.selectOne(new LambdaQueryWrapper<Order>()
                .eq(Order::getUserId, userId)
                .eq(Order::getId, orderId));
    }

    @Override
    public int countByOrderSn(Long userId, String orderSn) {
        return baseMapper.selectCount(new LambdaQueryWrapper<Order>()
                .eq(Order::getUserId, userId)
                .eq(Order::getOrderSn, orderSn));
    }

    @Override
    public String generateOrderSn(Long userId) {
        return IdWorker.getTimeId();
    }

    @Override
    public IPage<Order> queryByOrderStatus(Long userId, List<Short> orderStatus, Integer pageNo, Integer pageSize) {
        QueryWrapper<Order> query = new QueryWrapper<>();
        query.orderByDesc("add_time");
        query.eq("user_id", userId);
        query.eq(orderStatus != null, "order_status", orderStatus);

        Page<Order> page = new Page<>(pageNo, pageSize);
        return baseMapper.selectPage(page, query);
    }

    @Override
    public IPage<Order> querySelective(Long userId, String orderSn, LocalDateTime start, LocalDateTime end, List<Short> orderStatusArray, Integer pageNo, Integer pageSize) {
        QueryWrapper<Order> query = new QueryWrapper<>();
        query.eq(userId != null, "user_id", userId);
        query.eq(!StringUtils.isEmpty(orderSn), "order_sn", orderSn);
        query.gt(start != null, "add_time", start);
        query.lt(end != null, "add_time", end);

        if (orderStatusArray != null && orderStatusArray.size() != 0) {
            query.in("order_status", orderStatusArray);
        }
        Page<Order> page = new Page<>(pageNo, pageSize);
        return baseMapper.selectPage(page, query);
    }

    @Override
    public int count() {
       return baseMapper.selectCount(new QueryWrapper<Order>());
    }

    @Override
    public List<Order> queryUnpaid(int minutes) {
        return baseMapper.selectList(new LambdaQueryWrapper<Order>().eq(Order::getOrderStatus, OrderUtil.STATUS_CREATE));
    }

    @Override
    public List<Order> queryUnconfirm(int days) {
        LocalDateTime expired = LocalDateTime.now().minusDays(days);
        return baseMapper.selectList(new LambdaQueryWrapper<Order>()
                .eq(Order::getOrderStatus, OrderUtil.STATUS_SHIP).lt(Order::getShipTime, expired));
    }

    @Override
    public Order findBySn(String orderSn) {
        return baseMapper.selectOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderSn, orderSn));
    }

    @Override
    public Map<Object, Object> orderInfo(Long userId) {
        QueryWrapper<Order> query = new QueryWrapper<>();
        query.eq("user_id", userId);
        query.select("order_status","comments");
        List<Order> orders = baseMapper.selectList(query);

        int unpaid = 0;
        int unship = 0;
        int unrecv = 0;
        int uncomment = 0;
        for (Order order : orders) {
            if (OrderUtil.isCreateStatus(order)) {
                unpaid++;
            } else if (OrderUtil.isPayStatus(order)) {
                unship++;
            } else if (OrderUtil.isShipStatus(order)) {
                unrecv++;
            } else if (OrderUtil.isConfirmStatus(order) || OrderUtil.isAutoConfirmStatus(order)) {
                uncomment += order.getComments();
            } else {
                // do nothing
            }
        }

        Map<Object, Object> orderInfo = new HashMap<Object, Object>();
        orderInfo.put("unpaid", unpaid);
        orderInfo.put("unship", unship);
        orderInfo.put("unrecv", unrecv);
        orderInfo.put("uncomment", uncomment);
        return orderInfo;

    }

    @Override
    public List<Order> queryComment(int days) {
        QueryWrapper<Order> query = new QueryWrapper<>();
        query.gt("comments", 0);
        query.lt("confirm_time", LocalDateTime.now().minusDays(days));
        return baseMapper.selectList(query);
    }

    @Override
    public void updateAfterSaleStatus(Long orderId, Short statusReject) {
        Order order = new Order();
        order.setId(orderId);
        order.setAfterSaleStatus(statusReject);
        order.setUpdateTime(LocalDateTime.now());
        baseMapper.updateById(order);
    }

    @Override
    public Map<String, Object> queryVoSelective(String nickname, String consignee, String orderSn, LocalDateTime start,
                                                LocalDateTime end, List<Short> orderStatusArray, Integer pageNo, Integer pageSize) {
        List<String> querys = new ArrayList<>(4);
        if (!StringUtils.isEmpty(nickname)) {
            querys.add(" u.nickname like '%" + nickname + "%' ");
        }
        if (!StringUtils.isEmpty(consignee)) {
            querys.add(" o.consignee like '%" + consignee + "%' ");
        }
        if (!StringUtils.isEmpty(orderSn)) {
            querys.add(" o.order_sn = '" + orderSn + "' ");
        }
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if (start != null) {
            querys.add(" o.add_time >= '" + df.format(start) + "' ");
        }
        if (end != null) {
            querys.add(" o.add_time < '" + df.format(end) + "' ");
        }
        if (orderStatusArray != null && orderStatusArray.size() > 0) {
            querys.add(" o.order_status in (" + StringUtils.collectionToDelimitedString(orderStatusArray, ",") + ") ");
        }
        querys.add(" o.deleted = 0 and og.deleted = 0 ");
        String query = StringUtils.collectionToDelimitedString(querys, "and");

        Page<?> page = new Page<>(pageNo, pageSize);
        IPage<Map> list1 = baseMapper.getOrderIds(page, query);
        List<Integer> ids = new ArrayList<>();
        for (Map map : list1.getRecords()) {
            Integer id = (Integer) map.get("id");
            ids.add(id);
        }

        List<OrderVo> list2 = new ArrayList<>();
        if (!ids.isEmpty()) {
            querys.add(" o.id in (" + StringUtils.collectionToDelimitedString(ids, ",") + ") ");
            query = StringUtils.collectionToDelimitedString(querys, "and");
            list2 = baseMapper.getOrderList(query);
        }
        Map<String, Object> data = new HashMap<String, Object>(5);
        data.put("list", list2);
        data.put("total", list1.getTotal());
        data.put("page", list1.getCurrent());
        data.put("limit", page.getSize());
        data.put("pages", list1.getPages());
        return data;
    }

}
